<template>
  <div class="version-manager">
    <div class="version-card" v-loading="state.pageLoading">
      <div class="card-header">
        <h2 class="app-title">华商Go收银端</h2>
        <div class="version-info">
          <span class="version-label">
            <font-awesome-icon :icon="['fas', 'mobile']" class="version-icon" />
            当前版本
          </span>
          <el-input v-model="state.pdaNowVersion" placeholder="请输入版本号" class="version-input" />
        </div>
        <div class="version-info">
          <span class="version-label">
            <font-awesome-icon :icon="['fas', 'download']" class="version-icon" />
            下载地址：
          </span>
          <span class="version-input">{{ state.pdaDownloadUrl }}</span>
        </div>
      </div>
      <div class="card-actions">
        <el-button type="success" :loading="state.loading.pda.save" @click="handleSave('pda')">
          <font-awesome-icon :icon="['fas', 'save']" class="button-icon" />
          保存
        </el-button>
        <el-button type="primary" :loading="state.loading.pda.upgrade" @click="handleUpgrade('pda')">
          <font-awesome-icon :icon="['fas', 'arrow-up']" class="button-icon" />
          升级版本
        </el-button>
        <el-button :loading="state.loading.pda.downgrade" @click="handleDowngrade('pda')">
          <font-awesome-icon :icon="['fas', 'arrow-down']" class="button-icon" />
          降低版本
        </el-button>
      </div>
    </div>

    <div class="version-card" v-loading="state.pageLoading">
      <div class="card-header">
        <h2 class="app-title">华商Go商家端 - Android</h2>
        <div class="version-info">
          <span class="version-label">
            <font-awesome-icon :icon="['fas', 'mobile']" class="version-icon" />
            当前版本
          </span>
          <el-input v-model="state.shopAppNowVersion" placeholder="请输入版本号" class="version-input" />
        </div>
        <div class="version-info">
          <span class="version-label">
            <font-awesome-icon :icon="['fas', 'download']" class="version-icon" />
            下载地址：
          </span>
          <span class="version-input">{{ state.shopDownloadUrl }}</span>
        </div>
      </div>
      <div class="card-actions">
        <el-button type="success" :loading="state.loading.shop_android.save" @click="handleSave('shop_android')">
          <font-awesome-icon :icon="['fas', 'save']" class="button-icon" />
          保存
        </el-button>
        <el-button type="primary" :loading="state.loading.shop_android.upgrade" @click="handleUpgrade('shop_android')">
          <font-awesome-icon :icon="['fas', 'arrow-up']" class="button-icon" />
          升级版本
        </el-button>
        <el-button :loading="state.loading.shop_android.downgrade" @click="handleDowngrade('shop_android')">
          <font-awesome-icon :icon="['fas', 'arrow-down']" class="button-icon" />
          降低版本
        </el-button>
      </div>
    </div>

    <div class="version-card" v-loading="state.pageLoading">
      <div class="card-header">
        <h2 class="app-title">华商Go商家端 - iOS</h2>
        <div class="version-info">
          <span class="version-label">
            <font-awesome-icon :icon="['fas', 'laptop']" class="version-icon" />
            当前版本
          </span>
          <el-input v-model="state.shopAppNowVersionIOS" placeholder="请输入版本号" class="version-input" />
        </div>
        <div class="version-info">
          <span class="version-label">
            <font-awesome-icon :icon="['fas', 'download']" class="version-icon" />
            下载地址：
          </span>
          <span class="version-input">{{ state.shopIosDownloadUrl }}</span>
        </div>
      </div>
      <div class="card-actions">
        <el-button type="success" :loading="state.loading.shop_ios.save" @click="handleSave('shop_ios')">
          <font-awesome-icon :icon="['fas', 'save']" class="button-icon" />
          保存
        </el-button>
        <el-button type="primary" :loading="state.loading.shop_ios.upgrade" @click="handleUpgrade('shop_ios')">
          <font-awesome-icon :icon="['fas', 'arrow-up']" class="button-icon" />
          升级版本
        </el-button>
        <el-button :loading="state.loading.shop_ios.downgrade" @click="handleDowngrade('shop_ios')">
          <font-awesome-icon :icon="['fas', 'arrow-down']" class="button-icon" />
          降低版本
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import { FontAwesomeIcon } from "@fortawesome/vue-fontawesome";
import { library } from "@fortawesome/fontawesome-svg-core";
import {
  faMobileScreen,
  faStore,
  faDownload,
  faSave,
  faArrowUp,
  faArrowDown,
  faMobile,
  faLaptop
} from "@fortawesome/free-solid-svg-icons";
import { getPdaAppVersion, getShopAppVersion, getPdsDownloadUrl } from "@/api/modules/datawarn";

library.add(faMobileScreen, faStore, faDownload, faSave, faArrowUp, faArrowDown, faMobile, faLaptop);

type SystemType = "pda" | "shop_android" | "shop_ios";
type ActionType = "save" | "upgrade" | "downgrade";

const state = reactive({
  pdaNowVersion: "",
  shopAppNowVersion: "",
  shopAppNowVersionIOS: "",
  pdaDownloadUrl: "",
  shopDownloadUrl: "",
  shopIosDownloadUrl: "",
  loading: {
    pda: {
      save: false,
      upgrade: false,
      downgrade: false
    },
    shop_android: {
      save: false,
      upgrade: false,
      downgrade: false
    },
    shop_ios: {
      save: false,
      upgrade: false,
      downgrade: false
    }
  },
  pageLoading: false
});

const getInfo = async () => {
  try {
    state.pageLoading = true;
    const { version: pdaNowVersion } = await getPdaAppVersion({ op: 2 });
    const { data: pdaData } = await getPdsDownloadUrl({ system_type: "android", version: "1.0.1" });
    const {
      version: shopAppNowVersion,
      ios_version: shopAppNowVersionIOS,
      ios_url,
      android_url
    } = await getShopAppVersion({ op: 2 });
    state.pdaNowVersion = pdaNowVersion;
    state.pdaDownloadUrl = pdaData.version_info.download_url;
    state.shopAppNowVersion = shopAppNowVersion;
    state.shopDownloadUrl = android_url;
    state.shopIosDownloadUrl = ios_url;
    state.shopAppNowVersionIOS = shopAppNowVersionIOS;
  } finally {
    state.pageLoading = false;
  }
};

// 版本号升级逻辑
const upgradeVersion = (version: string): string => {
  const parts = version.split(".").map(Number);
  let carry = 1;
  for (let i = parts.length - 1; i >= 0; i--) {
    parts[i] += carry;
    if (parts[i] >= 10) {
      parts[i] = 0;
      carry = 1;
    } else {
      carry = 0;
      break;
    }
  }
  if (carry) parts.unshift(1);
  return parts.join(".");
};

// 版本号降低逻辑
const downgradeVersion = (version: string): string => {
  const parts = version.split(".").map(Number);
  let borrow = 1;
  for (let i = parts.length - 1; i >= 0; i--) {
    parts[i] -= borrow;
    if (parts[i] < 0) {
      parts[i] = 9;
      borrow = 1;
    } else {
      borrow = 0;
      break;
    }
  }
  if (parts[0] === 0) parts.shift();
  return parts.join(".");
};

// 设置加载状态
const setLoading = (system: SystemType, action: ActionType, loading: boolean) => {
  state.loading[system][action] = loading;
};

// 显示通知
const showNotification = (title: string, message: string, type: "success" | "error" = "success") => {
  ElMessage({
    message,
    type
  });
};

// 保存版本
const handleSave = async (system: SystemType) => {
  try {
    setLoading(system, "save", true);
    let version = "";
    let ios_version = "";

    if (system === "pda") {
      version = state.pdaNowVersion;
    } else if (system === "shop_android") {
      version = state.shopAppNowVersion;
      ios_version = state.shopAppNowVersionIOS;
    } else if (system === "shop_ios") {
      version = state.shopAppNowVersion;
      ios_version = state.shopAppNowVersionIOS;
    }
    if (system === "pda") {
      await getPdaAppVersion({ op: 1, version });
    } else {
      await getShopAppVersion({ op: 1, version, ios_version });
    }
    showNotification("提示", "保存成功");
  } catch (error) {
    showNotification("错误", "保存失败", "error");
  } finally {
    setLoading(system, "save", false);
  }
};

// 升级版本
const handleUpgrade = async (system: SystemType) => {
  try {
    setLoading(system, "upgrade", true);
    if (system === "pda") {
      state.pdaNowVersion = upgradeVersion(state.pdaNowVersion);
    } else if (system === "shop_android") {
      state.shopAppNowVersion = upgradeVersion(state.shopAppNowVersion);
    } else if (system === "shop_ios") {
      state.shopAppNowVersionIOS = upgradeVersion(state.shopAppNowVersionIOS);
    }
    await handleSave(system);
  } catch (error) {
    showNotification("错误", "升级失败", "error");
  } finally {
    setLoading(system, "upgrade", false);
  }
};

// 降低版本
const handleDowngrade = async (system: SystemType) => {
  try {
    setLoading(system, "downgrade", true);
    if (system === "pda") {
      state.pdaNowVersion = downgradeVersion(state.pdaNowVersion);
    } else if (system === "shop_android") {
      state.shopAppNowVersion = downgradeVersion(state.shopAppNowVersion);
    } else if (system === "shop_ios") {
      state.shopAppNowVersionIOS = downgradeVersion(state.shopAppNowVersionIOS);
    }
    await handleSave(system);
  } catch (error) {
    showNotification("错误", "降低失败", "error");
  } finally {
    setLoading(system, "downgrade", false);
  }
};

onMounted(() => {
  getInfo();
});
</script>

<style lang="scss" scoped>
.version-manager {
  min-height: auto;
  padding: 24px;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  .version-card {
    padding: 24px;
    margin-bottom: 24px;
    background: white;
    border-radius: 16px;
    box-shadow: 0 4px 20px rgb(0 0 0 / 5%);
    transition: transform 0.3s ease;
    &:hover {
      box-shadow: 0 8px 30px rgb(0 0 0 / 8%);
    }
    .card-header {
      margin-bottom: 24px;
      .app-title {
        display: flex;
        gap: 12px;
        align-items: center;
        margin-bottom: 16px;
        font-size: 20px;
        font-weight: 600;
        color: #2c3e50;
        .title-icon {
          width: 20px;
          height: 20px;
          font-size: 20px;
          color: var(--el-color-primary);
        }
      }
      .version-info {
        display: flex;
        gap: 12px;
        align-items: center;
        margin-bottom: 16px;
        .version-label {
          display: flex;
          gap: 8px;
          align-items: center;
          min-width: 140px;
          font-size: 14px;
          color: #64748b;
          .version-icon {
            width: 16px;
            height: 16px;
            font-size: 16px;
            color: var(--el-color-primary);
          }
        }
        .version-input {
          flex: 1;
          :deep(.el-input__wrapper) {
            box-shadow: 0 0 0 1px #e2e8f0;
            &:hover {
              box-shadow: 0 0 0 1px #cbd5e1;
            }
            &:focus-within {
              box-shadow: 0 0 0 1px #3b82f6;
            }
          }
        }
      }
    }
    .card-actions {
      display: flex;
      gap: 16px;
      :deep(.el-button) {
        display: flex;
        gap: 8px;
        align-items: center;
        padding: 8px 16px;
        .button-icon {
          width: 14px;
          height: 14px;
          font-size: 14px;
          transition: transform 0.3s ease;
        }
        &:hover .button-icon {
          transform: scale(1.1);
        }
      }
    }
  }
}
</style>
